# 屏幕输入的参数，从上游PM获取
param (
    [string]$user="",
    [string]$user_pwd=""
)

$DATA_BACKUP_AGENT_HOME = (Get-ChildItem env:DATA_BACKUP_AGENT_HOME).Value
$Location = $DATA_BACKUP_AGENT_HOME + "\DataBackup\ProtectClient\Plugins\GeneralDBPlugin\bin\applications\exchange\ps1_scripts"
Set-Location -Path $Location
[string]$common_file_path = (Get-Location).Path + "\Common.ps1"
[string]$ExchangeHost = hostname
[string]$pssession_name = "GetDAGGroupServers"

# 引用Common.ps1
. $common_file_path

# 建立连接
if (!(NewConnection $User $User_Pwd $pssession_name)) {
    return
}

try {
    # 获取DAG组
    $DAG_groups = Invoke-Command -Session $Session -ScriptBlock {Get-DatabaseAvailabilityGroup | Select-Object Name, Guid, Servers} -ErrorAction Stop
    $dag_uuid = ""
    $member_server_sum = 0
    # 空值判断
    if ($null -ne $DAG_groups) {
        # 遍历所有dag组
        foreach ($DAG_group in $DAG_groups) {
            $in_dag_group = $false
            # 判断服务器是否在DAG组中
            if ($null -ne $DAG_group.Servers -and 0 -ne $DAG_group.Servers.Count) {
                $temp_sum = 0
                foreach ($server in $DAG_group.Servers) {
                    $temp_sum++
                    if ([string]$server.Name -eq $ExchangeHost) {
                        $in_dag_group = $true
                    }
                }
                if ($in_dag_group) {
                    $dag_uuid = $DAG_group.Guid
                    $member_server_sum = $temp_sum
                    break
                }
            }
        }
    }

    # 赋值
    if ($member_server_sum -eq 0) {
        $member_server_sum = ""
    }
    $DAGDetail = @{
        dag_uuid = $dag_uuid
        member_server_sum = [string]$member_server_sum
    }
    # 拼接结构体
    $DAGListDetailResult = @{
        name = ""
        type = "Database"
        subType = "Exchange-database"
        extendInfo = $DAGDetail
    }
    # 省略空格和缩进,输出
    $DAGListDetailResult = [PSCustomObject]$DAGListDetailResult | ConvertTo-Json -Compress -Depth 10
    $DAGListDetailResult
} catch {
    $DAGDetail = @{
        access = "N"
        message = "Failed Get DAG Groups."
    }
    # 拼接结构体
    $DAGListDetailResult = @{
        name = ""
        type = "Database"
        subType = "Exchange-database"
        extendInfo = $DAGDetail
    }
    # 省略空格和缩进,输出
    $DAGListDetailResult = [PSCustomObject]$DAGListDetailResult | ConvertTo-Json -Compress -Depth 10
    $DAGListDetailResult
    ClosePSSession $pssession_name
    return @()
}

ClosePSSession $pssession_name
